//全选状态
let selectAll = false
/**
 * 购物车数据
 *      获取数据，数据来自localStorage
 */
function getShopCarData() {
    let storangeData = JSON.parse(localStorage.getItem('xiongmaoyouxuanCar'))
    console.log(storangeData)
    showShopCar(storangeData)
}

/**
 * 模板字符串渲染数据
 */
function showShopCar(datalist) {
    let str = `
        <tr>
            <th><input type="checkbox" name="selectAll" ${selectAll==true?'checked':''} id="selectAll">全选</th>
            <th>图片</th>
            <th>名称</th>
            <th>单价</th>
            <th>数量</th>
            <th>总价</th>
            <th>操作</th>
        </tr>
    `
    datalist.forEach(function (item) {
        str += `
            <tr data-id="${item.id}">
                <td><input type="checkbox" ${item.selectState==true?'checked':''} name="selectItem" id="selectItem"></td>
                <td><img src="${item.image}" alt=""></td>
                <td><div class="shopname">${item.title}</div></td>
                <td>￥${item.price}</td>
                <td><input type="button" name='minus' ${item.num==1?'disabled':''} value="-"><input type="text" name='amount' value="${item.num}"><input type="button" name='plus' value="+"></td>
                <td>￥${item.singleTotlePrice}</td>
                <td><span>删除</span></td>
            </tr>
        `
    })
    allTotlePrice()

    $('table').html(str)
    // checkboxState()
}

/**
 * 删除事件
 *      找到对应数据的id，从localStorage中删除
 */
$('table').on('click', 'span', function () {
    let isDel = confirm('确定删除吗？')
    if (isDel == false) {
        return
    }
    let id = $(this).parent().parent()[0].getAttribute('data-id')
    // console.log(id)
    let stoData = JSON.parse(localStorage.getItem('xiongmaoyouxuanCar'))
    let index = stoData.findIndex(item => item.id == id)
    stoData.splice(index, 1)
    localStorage.setItem('xiongmaoyouxuanCar', JSON.stringify(stoData))
    getShopCarData()
})

/**
 * 数量-1 
 *      找到对应id 改变localStorage里的数量
 */
$('table').on('click', 'input[name="minus"]', function () {
    let id = $(this).parent().parent()[0].getAttribute('data-id')
    console.log(id)
    let stoData = JSON.parse(localStorage.getItem('xiongmaoyouxuanCar'))
    let shop = stoData.find(item => item.id == id)
    shop.num--
    shop.singleTotlePrice = (shop.price * shop.num).toFixed(2)
    localStorage.setItem('xiongmaoyouxuanCar', JSON.stringify(stoData))
    getShopCarData()
})

/**
 * 数量加1 
 *      找到对应id 改变localStorage里的数量
 */
$('table').on('click', 'input[name="plus"]', function () {
    let id = $(this).parent().parent()[0].getAttribute('data-id')
    // console.log(id)
    let stoData = JSON.parse(localStorage.getItem('xiongmaoyouxuanCar'))
    let shop = stoData.find(item => item.id == id)
    shop.num++
    shop.singleTotlePrice = (shop.price * shop.num).toFixed(2)
    localStorage.setItem('xiongmaoyouxuanCar', JSON.stringify(stoData))
    getShopCarData()
})

/**
 * 手动修改数量 
 *      找到对应id 改变localStorage里的数量
 */
$('table').on('change', 'input[name="amount"]', function () {
    let num = $(this).val()

    let id = $(this).parent().parent()[0].getAttribute('data-id')
    // console.log(id)
    let stoData = JSON.parse(localStorage.getItem('xiongmaoyouxuanCar'))
    let shop = stoData.find(item => item.id == id)
    if (isNaN(num) || num < 0) {
        alert('请输入大于0的数字值！')
        num = shop.num
    }
    // console.log(num);
    shop.num = num
    shop.singleTotlePrice = (shop.price * shop.num).toFixed(2)
    localStorage.setItem('xiongmaoyouxuanCar', JSON.stringify(stoData))
    getShopCarData()
})

/**
 * 计算总价
 */
function allTotlePrice() {
    let stoData = JSON.parse(localStorage.getItem('xiongmaoyouxuanCar'))
    let allPrice = stoData.reduce((s, item) => s + parseFloat(item.singleTotlePrice), 0)
    $('.totlePrice').html('总价：￥' + allPrice.toFixed(2))
}

/**
 * 全选框
 */
function checkboxState() {
    $('table').on('click', 'input[name="selectAll"]', function () {
        let stoData = JSON.parse(localStorage.getItem('xiongmaoyouxuanCar'))
        console.log(stoData)
        selectAll = !selectAll
        if (selectAll) {
            stoData.map(item => item.selectState = true)
        } else {
            stoData.map(item => item.selectState = false)
        }
        localStorage.setItem('xiongmaoyouxuanCar', JSON.stringify(stoData))
        getShopCarData()
    })
}

/**
 * 商品项的复选框
 */
function checkboxItemState() {
    $('table').on('click', 'input[name="selectItem"]', function () {
        let stoData = JSON.parse(localStorage.getItem('xiongmaoyouxuanCar'))
        let id = $(this).parent().parent()[0].getAttribute('data-id')
        let shop = stoData.find(item => item.id == id)
        shop.selectState = !shop.selectState
        let isAll = stoData.every(item => item.selectState == true)
        if (isAll) selectAll = true
        else selectAll = false
        localStorage.setItem('xiongmaoyouxuanCar', JSON.stringify(stoData))
        getShopCarData()
    })
}

/**
 * 退出登录 清空localStorage
 */
$('.backLogin').click(function () {
    if (confirm('确定退出登陆吗？')) {
        location.href = 'login.html'
        localStorage.removeItem('xiongmaoUsers')
    }
})

/**
 * 显示用户信息
 */
function  userEmg(){
    let users = JSON.parse(localStorage.getItem('xiongmaoUsers'))
    let u = users.find(item => item.state == true)
    $('#user .uname').html(u.username)
}

checkboxState()
checkboxItemState()
getShopCarData()
userEmg()